<template>
  <div class="detail-page">
    <div class="mbd">
      <div class="bdc">
        <div class="detail">
          <!-- 左边主要内容区域 -->
          <div class="main">
            <!-- 顶部标题 -->
            <div class="job-header">
              <h1 class="job-title">
                {{ details.detailsList.name }}
              </h1>
            </div>
            
            <!-- 公司信息 -->
            <div class="company-info">
              <div class="company-logo">
                <!-- <i class="fas fa-building"></i> -->
                 <img class="yifu" :src="'https://58.dt12.cfd/'+ details.company.avatar"></img>
              </div>
              <div class="company-details">
                <h2 class="client_name">
                  <a href="#">{{ details.company.company_name }}</a>
                </h2>
                <div class="rating">
                  <div class="stars" v-for="(item, index) in companyStars.list" :key="index">
                    <img class="imgtwo" src="../../public/img/work/manxing.png"></img>
                  </div>
                  <img v-if="companyStars.start" class="imgtwo" src="../../public/img/work/banxing.png"></img>
                  <span class="rating-text">本人確認済み 発注ルールチェック済み </span>
                </div>
              </div>
            </div>
            
            <!-- 工作概要 -->
            <div class="cw-sub_head">
              <span>仕事の概要</span>
            </div>
            
            <table class="cw-table">
                <tbody>
              <tr>
                <th>報酬範囲</th>
                <td>{{ details.detailsList.salary_range }}</td>
              </tr>
              <tr>
                <th>掲載日</th>
                <td>{{ details.detailsList.createtime }}</td>
              </tr>
              <tr>
                <th>応募期限</th>
                <td>{{ details.detailsList.limit_time }}</td>
              </tr>
              </tbody>
            </table>
            
            <!-- 招募统计 -->
            <div class="cw-sub_head">
              <span>応募状況</span>
            </div>
            
            <div class="stats-container">
              <div class="stat-item">
                <div class="stat-label">応募した人</div>
                <div class="stat-value">{{ details.detailsList.persons_int }}人</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">契約した人</div>
                <div class="stat-value">{{ details.company.company_partnership }}人</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">募集人数</div>
                <div class="stat-value">{{ details.detailsList.recruits_people }}人</div>
              </div>
            </div>
            
            <!-- 工作详情（富文本内容） -->
            <div class="cw-sub_head">
              <span>仕事の詳細</span>
            </div>
            
            <div class="rich-text-content" v-html="details.content"></div>
            
            <!-- 客户信息 -->
            <div class="cw-sub_head">
              <span>クライアント情報</span>
            </div>
            
            <div class="client_detail_information_container">

              <div class="client_detail_information_left">
                <div class="company-logo">
                  <img class="yifu2" :src="'https://58.dt12.cfd/'+ details.company.avatar"></img>
                </div>
              </div>
              
              <div class="client_detail_information_right">
                <h3 class="client_main_title">{{ companyName }}</h3>
                
                <div class="client_sub_titles">
                  <div class="client_sub_title">
                    <img class="img-icon" src="../../public/img/work/dagou.png"></img>
                    <span>本人確認済み</span>
                  </div>
                  <div class="client_sub_title">
                    <img class="img-icon" src="../../public/img/work/dagou.png"></img>
                    <span>発注ルールチェック未回答</span>
                  </div>
                </div>
                
                <div class="client_stats">
                    <div class="client_stat_label">
                       <img class="img-icon" src="../../public/img/work/xing.png"></img>
                       総合評価
                    </div>
                    
                  <div class="client_stat">
                    <div class="client_stat_value">{{ companyRating }}</div>
                    <div class="stars">
                         <div class="stars" v-for="(item, index) in JobStars.list" :key="index">
                         <img class="imgtwo" src="../../public/img/work/manxing.png"></img>
                    </div>
                         <img v-if="JobStars.start" class="imgtwo" src="../../public/img/work/banxing.png"></img>
                    </div>
                  </div>
                  
                  <div class="client_stat client-stat-flex">
                    <div class="client_stat_label icon">
                      <img style="width: 20px;" src="../../public/img/work/gongdan.png"></img>
                       募集実績 
                    </div>
                    <div class="client_stat_value">{{ details.detailsList.apply_int }}<span style="font-size: 13px;">件</span></div>
                  </div>
                  
                  <div class="client_stat client-stat-flex">
                    <div class="client_stat_label icon">
                      <img class="imgtwo2" src="../../public/img/work/woshou.png"></img>
                      プロジェクト完了率
                    </div>
                    <div class="client_stat_value">{{ details.company.company_completion_rate }}</div>
                  </div>

                </div>
                
                <div class="read_more" @click="jobDetails">
                  <a href="#">会社詳細 <i class="fas fa-chevron-right"></i></a>
                </div>
              </div>
            </div>
            
            <!-- 申请按钮 -->
            <button class="button_highlight" @click="applyForJob">仕事を応募</button>
          </div>
          
          <!-- 右边侧边栏 -->
           <!-- web版 -->
           <div class="desktop-layout">
            <div class="sidebar">
        <h2 class="sidebar-title">
            <span v-if="jobTypes.length>0">{{ jobTypes[0].name }}</span>
        </h2>
        
        <div class="category-box">
            <div class="category-item" v-for="(item,index) in details.jobs_types" :key="index">{{ item.name }}</div>
        </div>
    </div>
           </div>
           <!-- 手机版 -->
           <div class="mobile-layout">

           </div>
      
    <!-- 浮窗 -->
     <CustomerService />
     <!-- オンラインサポート浮窗 -->
    <!-- <div class="customer_service" onclick="alert('オンラインサポートに接続中...')">
        <img class="img-icon-three" src="../../public/img/work/kefu.jpg"></img>
        <span>オンラインサポート</span>
    </div> -->

        </div>
      </div>
    </div>
    
    <!-- 基本応募情報入力弹窗 -->
    <el-dialog 
      v-model="showApplicationDialog" 
      title="基本応募情報を入力" 
      width="900px"
      height="auto"
      :before-close="cancelApplication"
    >
      <el-form :model="applicationForm" label-width="120px" class="application-form">
        <el-form-item label="氏名">
          <el-input v-model="applicationForm.name" placeholder="" />
        </el-form-item>
        
        <el-form-item label="電話番号">
          <el-input v-model="applicationForm.phone" placeholder="" />
        </el-form-item>
        
        <el-form-item label="住所">
          <el-input v-model="applicationForm.address" placeholder="" />
        </el-form-item>
        
        <el-form-item label="希望報酬">
          <el-input v-model="applicationForm.expected_reward" placeholder="予想される報酬を入力してください" />
        </el-form-item>
        
        <el-form-item label="納品数量">
          <el-input v-model="applicationForm.delivery_quantity" :min="0" placeholder="0" type="number" />
        </el-form-item>
        
        <el-form-item label="作業開始日">
          <el-date-picker
            v-model="applicationForm.start_time"
            type="date"
            placeholder="開始日を選択してください"
            style="width: 25%"
          />
        </el-form-item>
        
        <el-form-item label="作業終了日">
          <el-date-picker
            v-model="applicationForm.end_time"
            type="date"
            placeholder="開始日を選択してください"
            style="width: 25%"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelApplication">キャンセル</el-button>
          <el-button type="primary" @click="confirmApplication">確認する</el-button>
        </div>
      </template>
    </el-dialog>
     <el-button
    v-loading.fullscreen.lock="fullscreenLoading"
    style="border: none;"
  >
  </el-button>
  </div>
</template>

<script setup>
import { ref, computed,reactive} from 'vue';
import { onMounted } from 'vue';
import { useRouter,useRoute } from 'vue-router';
import { ElMessage,ElLoading } from 'element-plus'
import { jobsApi,orderApi} from '../api/index.js'
import richText from '../util/richTextUtil.js'
import CustomerService from '../components/CustomerService.vue'

const router = useRouter();
const route = useRoute();

const jobId = ref();
const companyId = ref();


const fullscreenLoading = ref(false)
const openFullScreen1 = () => {
  fullscreenLoading.value = true
  setTimeout(() => {
    fullscreenLoading.value = false
  }, 2000)
}


// 弹窗相关变量和表单数据已移除

onMounted(() => {
   if (route.query && route.query.id) {
    jobId.value = route.query.id;
    initData(route.query.id);
    positions();
  } else {
    console.error('路由参数 id 不存在');
  }
});
const jobTitle = ref('📢【新作登場】CELEN 高級和風浴衣 早割キャンペーン実施中📢');
    const companyName = ref('株式会社ジェーシーインターナショナルワークス');
    
    const companyRating = ref(5);

    const details = ref({
        detailsList:[],
        content:'',
        company:{},
        jobs_types:[]
    })
    // 职位类型数据
     const jobTypes = ref([])

    //公司评分
    const companyStars =ref({
        list:0,
        start:false,
    })
    //职位评分
    const JobStars =ref({
        list:'',
        start:false,
    })
    
    const positions = async ()=>{
        try {
    const res = await jobsApi.getJobsType()
    if (res.code === 1) {
      jobTypes.value = res.data
    //   // 初始化每个类别的折叠状态，默认展开
    //   jobTypes.value.forEach((category, index) => {
    //     categoryExpanded.value[index] = true
    //   })
    } else {
      ElMessage.error(res.msg || '获取职位类型失败')
    }
  } catch (error) {
    console.error('获取职位类型出错:', error)
    ElMessage.error('获取职位类型失败')
  }
    }

    const initData = async (jobId) => {
        console.log('sss',jobId)
        openFullScreen1()
      try {
        const res = await jobsApi.JobDetails({jobs_id:jobId})
        if (res.code === 1) {
          console.log(res.data.is_bank)
            details.value.detailsList = res.data;
            details.value.content = richText.formatRichText(res.data.content);
            details.value.company = res.data.company;
            details.value.jobs_types = res.data.jobs_type_data.jobs_types;
            companyId.value = res.data.company.job_int;
            console.log('ss',details.content)

            //处理评分
            const score = parseFloat(res.data.company.company_assess);
            const integerPart = Math.floor(score); // 整数部分
            const hasDecimal = score % 1 !== 0; // 是否有小数部分

            const score2 = parseFloat(res.data.company.company_quality);
            const integerPart2 = Math.floor(score2); // 整数部分
            const hasDecimal2 = score2 % 1 !== 0; // 是否有小数部分

            
            companyStars.value = {
                list: Array.from({ length: integerPart }, (_, i) => i + 1), // 创建 [1, 2, 3, ...] 的数组
                start: hasDecimal
              };
              JobStars.value = {
                list: Array.from({ length: integerPart2 }, (_, i) => i + 1), // 创建 [1, 2, 3, ...] 的数组
                start: hasDecimal2
              };
        } else {
            ElMessage.error(res.msg || '职位详情获取失败')
        }
    } catch (error) {
        ElMessage.error('职位详情获取失败')
    } 
    };
    //跳转公司详情页
    const jobDetails = () =>{
        router.push({
            path:'/JobDetails',
            query:{
                id:companyId.value
            }
        })
    }
    // 弹窗相关变量
    const showApplicationDialog = ref(false);
    const applicationForm = ref({
      name: '',
      phone: '',
      address: '',
      expected_reward: '',
      delivery_quantity: 0,
      start_time: '',
      end_time: ''
    });

    // 申请工作方法
    const applyForJob = () => {
        const token = localStorage.getItem('token')
        if (!token) {
            ElMessage.error({
                message: `<b>「システム通知」</b><br>
「まずログインしてから申請してください。」`,
                dangerouslyUseHTMLString: true
            });
            // 3秒后跳转到登录页面
            setTimeout(() => {
                router.push({
                    path: '/login',
                })
            }, 3000)
            return
        }
        
        // 检查is_bank值
        if (details.value.detailsList.is_bank === 0) {
            ElMessage.error({
                message: `「銀行口座が未登録です」<br>
お客様のアカウントには、現在ご利用可能な銀行口座が登録されておりません。
<br>
お手数ですが、銀行口座を追加してから、再度お試しください。」`,
                dangerouslyUseHTMLString: true
            });
            // 3秒后跳转到银行账户页面
            setTimeout(() => {
                router.push({
                    path: '/user/bankaccount',
                })
            }, 3000)
            return
        }
        
        // 显示申请弹窗
        showApplicationDialog.value = true;
    }

    // 取消申请
    const cancelApplication = () => {
        showApplicationDialog.value = false;
        // 重置表单
        applicationForm.value = {
            name: '',
            phone: '',
            address: '',
            expected_reward: '',
            delivery_quantity: 0,
            start_time: '',
            end_time: ''
        };
    }

    // 确认申请
    const confirmApplication = async () => {
        // 这里可以添加表单验证逻辑
   try {
    // 再次检查用户是否已登录
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.warning('登录已过期，请重新登录后再申请工作')
      showApplicationDialog.value = false
      // 跳转到登录页面，并设置重定向回当前页面
      router.push({
        path: '/login',
        query: { redirect: '/findwork' }
      })
      return
    }

    // 验证表单
    if (!applicationForm.value.name || !applicationForm.value.phone || !applicationForm.value.address ||
      !applicationForm.value.expected_reward || !applicationForm.value.start_time || !applicationForm.value.end_time) {
      ElMessage.error('職種概要を入力してください')
      return
    }

    // 检测希望报酬是否包含小数点
    if (applicationForm.value.expected_reward && applicationForm.value.expected_reward.toString().includes('.')) {
      ElMessage.error('小数点を含めることはできません')
      return
    }

    // 确保jobs_id存在
    if (!jobId.value) {
      ElMessage.warning('职位ID不存在，请重新选择职位')
      return
    }

    const data = {
      jobs_id: jobId.value,
      ...applicationForm.value
    }

    console.log('提交的数据:', data)

    const res = await orderApi.createOrder(data)
    if (res.code === 1) {
      ElMessage.success('申请提交成功，请进行签名确认')
    //   orderInfo.value = res.data
    //   showApplicationDialog.value = false
    //   signDialogVisible.value = true
    } else if (res.code === 401) {
      ElMessage.warning('登录已过期，请重新登录后再申请工作')
      showApplicationDialog.value = false
      // 跳转到登录页面，并设置重定向回当前页面
      router.push({
        path: '/login',
        query: { redirect: '/findwork' }
      })
    } else if (res.code === 1001) {
      ElMessage.warning(res.msg || '銀行カードが追加されていません')
      showApplicationDialog.value = false
      // 跳转到银行账户页面，并设置重定向回当前页面
      router.push({
        path: '/user/bankaccount',
        query: { redirect: '/find-work' }
      })
    } else {
      ElMessage.error(res.msg || '申请提交失败')
    }
  } catch (error) {
    console.error('提交申请出错:', error)
    ElMessage.error('申请提交失败')
  }
    }
    // 简单的交互效果
        document.querySelectorAll('.category-item').forEach(item => {
            item.addEventListener('click', function() {
                this.style.color = '#0060a9';
                this.style.fontWeight = 'bold';
            });
        });
    
// 弹窗相关事件监听器已移除


</script>

<style scoped>
* {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Meiryo, system-ui, -apple-system, sans-serif;
        }
        .desktop-layout {
            display: block;
        }
       
        .mobile-layout {
            display: none;
        }
        body {
            background-color: #f5f5f5;
            color: #333;
            line-height: 1.6;
            padding: 20px;
        }
        /* 小图标 */
        .img-icon{
            width: 13px;
            height: 13px;
        }
        .imgtwo2{
            width: 25px;
        }
        .img-icon-two{
            width: 50px;
        }
        .imgtwo{
            width: 15px;
        }
        .img-icon-three{
            width: 28px;
            height: 28px;
        }
        .icon{
            margin-right: 20px;
            display: flex;
            
        }
        .yifu{
            width: 60px;
            height: 58px;
        }
        .yifu2{
            width: 80px;
            height: 80px;
        }
        .detail-page {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .mbd {
            display: flex;
            gap: 20px;
            margin-top: 20px;
        }
        
        .bdc {
            flex: 1;
            background: white;
            border-radius: 8px;
            /* box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); */
            overflow: hidden;
        }
        
        .detail {
            display: flex;
        }
        
        .main {
            flex: 1;
            padding: 20px;
        }
        
        
        .job-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 20px;
            padding-bottom: 15px;
            /* border-bottom: 2px solid #e7e7e7; */
        }
        
        .job-title {
            font-size: 24px;
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .company-info {
            display: flex;
            gap: 20px;
            margin-bottom: 25px;
            padding-bottom: 20px;
            /* border-bottom: 1px solid #e7e7e7; */
        }
        
        .company-logo {
            width: 80px;
            height: 80px;
            /* background-color: #f0f0f0; */
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 32px;
            color: #0068b7;
        }
        
        .company-details {
            flex: 1;
        }
        
        .client_name a {
            color: #085591;
            text-decoration: none;
            font-size: 20px;
            font-weight: bold;
        }
        
        .rating {
            display: flex;
            align-items: center;
            /* gap: 10px; */
            margin-top: 10px;
        }
        
        .stars {
            display: flex;
            align-items: center;
            color: #ffc107;
        }
        
        .rating-text {
            font-size: 14px;
            color: #666;
        }
        .cw-sub_head {
            margin: 25px 0 15px;
            font-size: 18px;
            font-weight: bold;
            border-bottom: 1px solid #ddd;
        }
         .cw-sub_head span {
            color: #0060a9;
            display: inline-block;
            margin: 0 0 -1px;
            padding: 5px 1px;
            border-bottom: 3px solid #0068b7;
        }
        .cw-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0 25px;
        }
        
        .cw-table th {
            vertical-align: middle;
            border-top: 1px solid #ddd;
            border-bottom: 1px solid #ddd;
            text-align: center;
            opacity: .8;
            background-color: #f7f7f7;
            white-space: nowrap;
            width: 100px;
            padding: 8px 16px;
            font-size: 14px;
            line-height: 1.6;
        }
        
        .cw-table td {
            border: 1px solid #ddd;
            word-break: break-word;
            overflow-wrap: break-word;
            vertical-align: middle;
            padding: 8px 16px;
            font-size: 14px;
            line-height: 1.6;
        }
        
        .stats-container {
            display: flex;
            /* justify-content: space-around; */
            /* margin: 20px 0;
            padding: 15px; */
            /* background-color: #f9f9f9; */
            /* border-radius: 8px; */
        }
        
        .stat-item {
            display: flex;
            align-items: center;
            margin-right: 50px;
        }
        
        .stat-value {
          margin-left: 10px;
        }
        
        .stat-label {
           font-size: 14px;
           line-height: 1.6;
           color: #333;
           font-weight: 800;
        }

        @media (max-width: 900px) {
             .stats-container {
            display: flex;
            flex-direction:row; 
            flex-wrap:wrap;
        }
        }
        .rich-text-content {
            margin: 25px 0;
            padding: 20px;
            /* border: 1px solid #e7e7e7; */
            /* border-radius: 8px; */
            /* background-color: #fafafa; */
        }
        
        .client_detail_information_container {
            margin-top: 16px;
            padding: 24px 16px;
            border-radius: 4px;
            border: solid 1px #ccc;
            display: flex;
            gap: 20px;
        }
        
        .client_detail_information_left {
            flex-shrink: 0;
        }
        
        .client_detail_information_right {
            flex: 1;
        }
        
        .client_main_title {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 15px;
        }
        
        .client_sub_titles {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .client_sub_title {
            display: flex;
            align-items: center;
            gap: 5px;
            font-size: 14px;
            color: #666;
        }
        
        .client_stats {
            display: flex;
            gap: 10%;
            margin: 20px 0 ;
            padding-bottom: 20px;
            border-bottom: 1px solid #e7e7e7;
        }
        
        .client_stat {
            text-align: center;
        }
        .client-stat-flex{
          display: flex;
          align-items: center;
        }
        
        .client_stat_value {
            font-size: 20px;
            font-weight: bold;
            margin-top: -10px;
        }
        
        .client_stat_label {
            font-size: 12px;
            color: #333;
        }
        
        .read_more {
            text-align: right;
            margin-top: 15px;
        }
        
        .read_more a {
            color: #0b71c1;
            text-decoration: none;
            font-size: 14px;
        }
        
        .button_highlight {
            display: block;
            width: 200px;
            margin: 30px auto;
            padding: 12px 20px;
            color: #fff;
            text-shadow: 0 -1px 0 rgba(0, 0, 0, .25);
            background-image: linear-gradient(to bottom, #f2850c, #f26d0c);
            background-repeat: repeat-x;
            background-color: #f2850c;
            border: 1px solid #e56f19;
            border-radius: 4px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            text-align: center;
        }
        
        .button_highlight:hover {
            background-image: linear-gradient(to bottom, #f26d0c, #e65c00);
        }
        
        @media (max-width: 900px) {
            .detail {
                flex-direction: column;
            }
            
            .main {
                border-right: none;
                border-bottom: 1px solid #e7e7e7;
            }
            
          .client-stat-flex{
          display: flex;
          align-items: center;
          justify-content: space-between !important;
          margin-top: 20px;
          width: 100%;
        }
            .company-info {
                flex-direction: column;
            }
            
            .client_detail_information_container {
                /* flex-direction: column; */
            }
            .client_stat {
            text-align: center;
            flex-wrap: wrap;
                justify-content: space-between;
        }
            .client_stats {
                flex-wrap: wrap;
                justify-content: space-between;
                
            }
        }
        /*右侧内容 */
        .sidebar {
            width: 250px;
            background: white;
            border-radius: 8px;
            padding: 20px;
        }
        
        .sidebar-title {
            margin: 0 0 15px;
            font-size: 16px;
            font-weight: bold;
        }
        
        .sidebar-title span {
            color: #0060a9;
            display: inline-block;
            margin: 0 0 -1px;
            padding: 5px 1px;
            border-bottom: 3px solid #0068b7;
        }
        
        .category-box {
            border: 1px solid #e7e7e7;
            border-radius: 4px;
            padding: 15px 0px 15px 15px;
            margin-bottom: 20px;
            background-color: #FCFCFC;
        }
        
        .category-item {
            padding: 10px 0;
            font-size: 13px;
            display: flex;
            align-items: center;
            color: #085591;
        }
        
        .category-item:last-child {
            border-bottom: none;
        }
        
        .category-item:hover {
            background-color: #f9f9f9;
            cursor: pointer;
        }
        /* 客服 */
         .customer_service {
            position: fixed;
            bottom: 158px;
            right: 0;
            max-width: 2.9375rem;
            display: inline-flex;
            flex-direction: column;
            align-items: center;
            padding: .875rem .71875rem;
            color: #0068b5;
            font-size: 1rem;
            line-height: 1.3125;
            font-weight: 600;
            letter-spacing: .08313em;
            background-color: #fff;
            border-top-left-radius: .625rem;
            border-bottom-left-radius: .625rem;
            box-shadow: 0 0 1.25rem #0068b533;
            transition: .25s ease;
            transition-property: background-color, box-shadow;
            backface-visibility: hidden;
            cursor: pointer;
            z-index: 1000;
        }
        
        .customer_service:hover {
            background-color: #f0f7ff;
            box-shadow: 0 0 1.875rem #0068b566;
        }
        
        .customer_service span {
            writing-mode: vertical-rl;
            text-orientation: mixed;
        }
        
        /* 申请弹窗样式 */
        .application-form {
            padding: 20px 0;
        }
        
        .application-form .el-form-item {
            margin-bottom: 20px;
        }
        
        .application-form .el-form-item__label {
            font-weight: 500;
            color: #333;
        }
        
        .application-form .el-input__wrapper {
            border-radius: 4px;
        }
        
        .dialog-footer {
            text-align: center;
            padding-top: 20px;
        }
        
        .dialog-footer .el-button {
            min-width: 100px;
            margin: 0 10px;
        }
/* 手机模式 */
@media (max-width: 768px) {
 .desktop-layout {
                display: none;
            }
            
            .mobile-layout {
                display: block;
            }
  
}





</style>